// 人脸检测功能使用tracking.js库
document.addEventListener('DOMContentLoaded', function() {
  // 检查tracking.js是否已加载
  if (typeof tracking === 'undefined') {
    document.getElementById('result').textContent = '错误：tracking.js库未加载';
    console.error('tracking.js库未加载');
    return;
  }

  // 检查是否加载了人脸检测数据
  if (typeof tracking.ObjectTracker === 'undefined') {
    document.getElementById('result').textContent = '错误：人脸检测模块未加载';
    console.error('人脸检测模块未加载');
    return;
  }

  const imageInput = document.getElementById('image-input');
  const preview = document.getElementById('preview');
  const result = document.getElementById('result');
  const canvas = document.getElementById('canvas');
  
  // 检查Canvas支持
  if (!canvas.getContext) {
    result.textContent = '错误：浏览器不支持Canvas';
    console.error('浏览器不支持Canvas');
    return;
  }
  
  const context = canvas.getContext('2d');

  imageInput.addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = function(event) {
      preview.src = event.target.result;
      preview.style.display = 'block';
      
      preview.onload = function() {
        try {
          // 设置canvas尺寸与图片一致
          canvas.width = preview.naturalWidth;
          canvas.height = preview.naturalHeight;
          canvas.style.display = 'block';
          preview.style.display = 'none';
          
          detectFaces(preview);
        } catch (e) {
          console.error('图片处理出错:', e);
          result.textContent = '图片处理出错，请重试';
        }
      };
      
      preview.onerror = function() {
        result.textContent = '图片加载失败，请重试';
        console.error('图片加载失败');
      };
    };
    
    reader.onerror = function() {
      result.textContent = '文件读取失败，请重试';
      console.error('文件读取失败');
    };
    
    reader.readAsDataURL(file);
  });

  function detectFaces(image) {
    result.textContent = '检测中...';
    
    try {
      // 使用tracking.js进行人脸检测
      const tracker = new tracking.ObjectTracker('face');
      tracker.setInitialScale(4);
      tracker.setStepSize(2);
      tracker.setEdgesDensity(0.1);
      
      // tracking.js需要在canvas上进行检测
      context.drawImage(image, 0, 0, canvas.width, canvas.height);
      
      let trackEventFired = false;
      let trackTimeout;
      
      // 进行人脸检测
      tracker.on('track', function(event) {
        // 清除超时定时器
        clearTimeout(trackTimeout);
        
        // 防止事件被多次触发
        if (trackEventFired) {
          console.log('跟踪事件已触发，跳过重复事件');
          return;
        }
        trackEventFired = true;
        
        console.log('检测到的人脸数据:', event.data);
        const faces = event.data;
        const faceCount = faces.length;
        
        if (faceCount === 0) {
          result.textContent = '未检测到人脸';
        } else {
          result.textContent = `检测到 ${faceCount} 个人脸`;
          // 在图片上标记检测到的人脸
          drawFaces(faces);
        }
      });
      
      // 在canvas上进行人脸检测
      console.log('开始人脸检测');
      tracking.track(canvas, tracker);
      
      // 添加超时处理，防止检测过程卡住
      trackTimeout = setTimeout(() => {
        if (!trackEventFired) {
          result.textContent = '检测超时，请重试';
          console.log('检测超时');
        }
      }, 10000);
    } catch (error) {
      console.error('人脸检测出错:', error);
      result.textContent = '检测失败，请重试';
    }
  }
  
  function drawFaces(faces) {
    try {
      // 绘制人脸矩形框
      context.strokeStyle = '#00ff00';
      context.lineWidth = 2;
      
      faces.forEach(function(face) {
        context.strokeRect(face.x, face.y, face.width, face.height);
      });
    } catch (e) {
      console.error('绘制人脸框出错:', e);
    }
  }
});